package com.yxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.dao.PersonMapper;
import com.yxy.dao.TableUserMapper;
import com.yxy.dto.AdminUserDto;
import com.yxy.dto.RoleDto;
import com.yxy.dto.TableDepartmentDto;
import com.yxy.dto.TableUserDto;
import com.yxy.feign.VO.AdminUserInToken;

import com.yxy.model.AdminUser;
import com.yxy.model.Role;
import com.yxy.model.TableDepartment;
import com.yxy.model.TableUser;
import com.yxy.utils.TenantHelper;
import com.yxy.utils.TokenCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Service
public class TableUserService {



  @Autowired
  private com.yxy.service.TableDepartmentService TableDepartmentService;


  @Resource
  private HttpServletRequest request;

  @Autowired
  private TokenCheckUtil tokenCheckUtil;

  @Resource
  private PersonMapper personMapper;
  @Resource
  private TableUserMapper tableUserMapper;


  @Autowired
  private RoleService roleService;

  @Value("${unionAuthUrl}")
  private String unionAuthUrl;


  @Autowired
  private TenantHelper tenantHelper;


  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public TableUser save(TableUserDto pojo) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();

    TableUser entity = new TableUser();
    BeanUtils.copyProperties(pojo, entity);
    entity.setCreateDate(new Date());
    entity.setCreateUserId(adminUser.getAdminUser().getId());
    entity.setCreateUserName(adminUser.getAdminUser().getUsername());
    RoleDto query = new RoleDto();
    query.setRoleName(pojo.getRoleName());
    Role role = roleService.getRoleInfoByName(query);
    AdminUserDto adminUser1 = new AdminUserDto();
    List<Long> selectedTenantIdList = new ArrayList<>();
    List<Long> selectedRoleIdList = new ArrayList<>();
    selectedTenantIdList.add(pojo.getTenantId());
    selectedRoleIdList.add(role.getId());
    adminUser1.setName(pojo.getUserName());
    adminUser1.setUsername(pojo.getUserAccount());
    adminUser1.setPassword(pojo.getUserAccount());
    adminUser1.setDescription(pojo.getPosition());
    adminUser1.setSelectedTenantIdList(selectedTenantIdList);
    adminUser1.setSelectedRoleIdList(selectedRoleIdList);
//    selectedTenantIdList.remove(0);
//    selectedRoleIdList.remove(0);

    System.out.println("unionAuthUrl:" + unionAuthUrl);

    String token = this.authLogin();


    String str = JSON.toJSONString(adminUser1);
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("X-Token", token);
    HttpEntity<String> formEntity = new HttpEntity<String>(str, headers);
    System.out.println("发送的json串:" + str);
    String result = restTemplate.postForEntity(unionAuthUrl + "/app-user/createOrUpdate", formEntity, String.class).getBody();
    System.out.println("数据发送返回结果：" + result);

    JSONObject jsonObject = JSONObject.parseObject(result);
    try {
      Map jsonToMap = JSONObject.parseObject(jsonObject.toJSONString());
      String content = jsonToMap.get("content").toString();

      Long id;
      if (content != null) {
        JSONObject jsonObjectToken = JSONObject.parseObject(content);
        Map jsonToMapToken = JSONObject.parseObject(jsonObjectToken.toJSONString());
        String idStr = jsonToMapToken.get("id").toString();
        id = Long.parseLong(idStr);
        entity.setAuthId(id);
        tableUserMapper.insertSelective(entity);
      } else {

      }
      return entity;
    } catch (Exception ne) {
      return null;
    }

  }


  public String authLogin() {

    JSONObject json = new JSONObject();
    json.put("username", "superAdmin");
    json.put("password", "123456");

    String str = JSON.toJSONString(json);
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    HttpEntity<String> formEntity = new HttpEntity<String>(str, headers);
    System.out.println("发送的json串:" + str);
    String result = restTemplate.postForEntity(unionAuthUrl + "/login/in", formEntity, String.class).getBody();
    System.out.println("数据发送返回结果：" + result);

    JSONObject jsonObject = JSONObject.parseObject(result);
    Map jsonToMap = JSONObject.parseObject(jsonObject.toJSONString());
    String content = jsonToMap.get("content").toString();

    if (content != null) {
      JSONObject jsonObjectToken = JSONObject.parseObject(content);
      Map jsonToMapToken = JSONObject.parseObject(jsonObjectToken.toJSONString());
      String token = jsonToMapToken.get("token").toString();
      return token;
    } else {
      return null;
    }


  }


  //编辑数据
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public TableUser modify(TableUserDto pojo) throws BusinessException {
    TableUser gpfMarketProductcode = tableUserMapper.selectByPrimaryKey(pojo.getId());
    if (gpfMarketProductcode == null) {
      throw new BusinessException(501, "修改数据失败，未找到Id为[" + pojo.getId() + "]的数据");
    }

    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableUser entity = new TableUser();
    BeanUtils.copyProperties(pojo, entity);
    entity.setUpdateDate(new Date());
    try {
      entity.setUpdateUserId(adminUser.getAdminUser().getId());
    } catch (NullPointerException ne) {
      entity.setUpdateUserId(Long.parseLong("3"));
    }
    try {
      entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    } catch (NullPointerException ne) {
      entity.setUpdateUserName("admin");
    }
    entity.setCreateDate(new Date());
    entity.setCreateUserId(adminUser.getAdminUser().getId());
    entity.setCreateUserName(adminUser.getAdminUser().getUsername());
    RoleDto query = new RoleDto();
    query.setRoleName(pojo.getRoleName());
    Role role = roleService.getRoleInfoByName(query);
    String token = this.authLogin();
    AdminUserDto adminUser1 = new AdminUserDto();

    List<Long> selectedTenantIdList = new ArrayList<>();
    List<Long> selectedRoleIdList = new ArrayList<>();
    selectedTenantIdList.add(pojo.getTenantId());
    selectedRoleIdList.add(role.getId());
    adminUser1.setId(pojo.getAuthId());
    adminUser1.setName(pojo.getUserName());
    adminUser1.setUsername(pojo.getUserAccount());
    adminUser1.setPassword(pojo.getUserAccount());
    adminUser1.setDescription(pojo.getPosition());
    adminUser1.setSelectedTenantIdList(selectedTenantIdList);
    adminUser1.setSelectedRoleIdList(selectedRoleIdList);

    String str = JSON.toJSONString(adminUser1);
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("X-Token", token);
    HttpEntity<String> formEntity = new HttpEntity<String>(str, headers);
    System.out.println("发送的json串:" + str);
    String result = restTemplate.postForEntity(unionAuthUrl + "/app-user/createOrUpdate", formEntity, String.class).getBody();
    System.out.println("数据发送返回结果：" + result);
    tableUserMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }


  //获取加工企业登记审核列表
  public List<TableUser> getlist(TableUserDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    Long tenantId = query.getTenantId();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
    } else {
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      tenantIdList.add(tenantId);
    }

    if(query.getDepartmentName1()!=null&&!"".equals(query.getDepartmentName1())){
      query.setDepartmentName(null);
    }

    query.setTenantIdList(tenantIdList);
    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<TableUser> dbResult = tableUserMapper.selectList(query);
    return dbResult;
  }


  //获取加工企业登记审核列表
  public List<TableDepartment> getlistByDepartment(TableDepartmentDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    Long tenantId = query.getTenantId();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
    } else {
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      tenantIdList.add(tenantId);
    }


    TableDepartmentDto tableDepartmentDto = new TableDepartmentDto();
    TableUserDto tableUserDto = new TableUserDto();
    List<TableDepartment> departmentList = TableDepartmentService.getlist(tableDepartmentDto);
    for(int i = 0;i<departmentList.size();i++){
      tableUserDto.setDepartmentName(departmentList.get(i).getDepartmentName());
      List<TableUser> dbResult = tableUserMapper.selectList(tableUserDto);
      if(dbResult.size()>0){
        departmentList.get(i).setUserList(dbResult);
      }
    }

    return departmentList;
  }

  //获取加工企业登记审核列表
  public List<TableUser> getListNoName(TableUserDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    Long tenantId = query.getTenantId();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
    } else {
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      tenantIdList.add(tenantId);
    }

    if(query.getDepartmentName1()!=null&&!"".equals(query.getDepartmentName1())){
      query.setDepartmentName(null);
    }

    query.setTenantIdList(tenantIdList);
    List<TableUser> dbResult = tableUserMapper.selectListNoName(query);
    return dbResult;
  }


  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void delete(String Id, Integer status) throws BusinessException {
    String arr[] = Id.split(",");
    List<Long> idlist = new ArrayList<>();
    for (int i = 0; i < arr.length; i++) {
      Long p = Long.parseLong(arr[i]);
      idlist.add(p);
    }
    if (CollectionUtils.isEmpty(idlist)) {
      throw new BusinessException(501, "删除失败，id为null");
    }
    int i = tableUserMapper.deleteByIds(idlist);
    if (i <= 0) {
      throw new BusinessException(501, "删除数据失败");
    }
  }


}
